package com.ruoyi.business.utils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

public class EChartsImgUtil {
    // node服务地址（需部署node+echarts-convert服务）
    private static final String ECHARTS_NODE_URL = "http://localhost:6666/convert";

    /**
     * 生成ECharts图片
     * @param optionJson ECharts option的json字符串
     * @param width 宽
     * @param height 高
     * @return 图片字节
     */
    public static byte[] generateEChartsImg(String optionJson, int width, int height) {
        try {
            URL url = new URL(ECHARTS_NODE_URL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.setRequestProperty("Content-Type", "application/json");
            String payload = String.format("{\"option\":%s,\"width\":%d,\"height\":%d}", optionJson, width, height);
            try (OutputStream os = conn.getOutputStream()) {
                os.write(payload.getBytes("UTF-8"));
            }
            try (InputStream is = conn.getInputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
                byte[] buf = new byte[4096];
                int len;
                while ((len = is.read(buf)) != -1) {
                    baos.write(buf, 0, len);
                }
                return baos.toByteArray();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 构造饼图option
     */
    public static String buildPieOption(String title, String[] names, double[] values) {
        StringBuilder sb = new StringBuilder();
        sb.append("{title:{text:'").append(title).append("',left:'center'},");
        sb.append("tooltip:{trigger:'item'},legend:{orient:'vertical',left:'left'},");
        sb.append("series:[{name:'比例',type:'pie',radius:'60%',data:[");
        for (int i = 0; i < names.length; i++) {
            if (i > 0) sb.append(",");
            sb.append(String.format("{value:%s,name:'%s'}", values[i], names[i]));
        }
        sb.append("]}]}\n");
        return sb.toString();
    }

    /**
     * 构造柱状图option
     */
    public static String buildBarOption(String title, String[] categories, int[] values) {
        StringBuilder sb = new StringBuilder();
        sb.append("{title:{text:'").append(title).append("',left:'center'},");
        sb.append("tooltip:{},legend:{data:['人数']},");
        sb.append("xAxis:{data:[");
        for (int i = 0; i < categories.length; i++) {
            if (i > 0) sb.append(",");
            sb.append("'" + categories[i] + "'");
        }
        sb.append("]},yAxis:{},series:[{name:'人数',type:'bar',data:[");
        for (int i = 0; i < values.length; i++) {
            if (i > 0) sb.append(",");
            sb.append(values[i]);
        }
        sb.append("]}]}\n");
        return sb.toString();
    }
} 